import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/manage/adjust/adjustmodel.dart';
import 'package:opene/ui/manage/cyclecount/ccskusubmitscreen.dart';
import 'package:opene/ui/manage/cyclecount/ccskutrkscreen.dart';
import 'package:toast/toast.dart';

class CCSkuScreen extends StatelessWidget {
  CycleCountSku cycleCountSku;

  CCSkuScreen({this.cycleCountSku});

  @override
  Widget build(BuildContext context) {
    return CCSkuScreenPage(cycleCountSku: cycleCountSku);
  }
}

class CCSkuScreenPage extends StatefulWidget {
  CycleCountSku cycleCountSku;

  CCSkuScreenPage({this.cycleCountSku});

  @override
  _CCSkuScreenPageState createState() => _CCSkuScreenPageState(cycleCountSku: cycleCountSku);
}

class _CCSkuScreenPageState extends BaseState<CCSkuScreenPage> {
  CycleCountSku cycleCountSku;

  _CCSkuScreenPageState({this.cycleCountSku});

  final TextEditingController dateController = TextEditingController();
  final controller = ScrollController();

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "CycleCount: Scan LPN";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration(milliseconds: 300), () {
      setState(() {
        getTallyContainerNo();
      });
    });
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Text(
                    "Barcode: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                  Text(
                    "SKU: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                ],
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      Utils.getStringisEmpty(cycleCountSku.barcode),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                    Text(
                      Utils.getStringisEmpty(cycleCountSku.sku),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                  ],
                ),
              ),
            ],
          ),
          Container(
            margin: EdgeInsets.only(top: 10, left: 0, right: 0),
            child: Row(
              children: [
                Expanded(
                  flex: 1, //设置权重
                  child: GestureDetector(
                    onTap: () {
                      // 请求焦点
                      FocusScope.of(context).requestFocus(FocusNode());
                      if (type == 1) {
                        return;
                      }
                      setState(() {
                        type = 1;
                        textEditingController.text = "";
                        cycleCountSku.total = 0;
                        cycleCountSku.lpnQty = 0;
                        cycleCountSku.inventoryList = null;
                        getTallyContainerNo();
                      });
                    },
                    child: Container(
                      padding: EdgeInsets.all(5),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: type == 1 ? MyAppTheme.nearlyBlue : MyAppTheme.white, // 背景颜色
                        borderRadius: BorderRadius.only(topLeft: Radius.circular(8.0), bottomLeft: Radius.circular(8.0)), // 圆角半径
                        border: Border.all(
                          color: MyAppTheme.nearlyBlue, // 边框颜色
                          width: 0.5, // 边框宽度
                        ),
                      ),
                      child: Text(
                        'Normal',
                        style: type == 1 ? MyAppTheme.textWhite14 : MyAppTheme.text,
                      ), // 子控件，如果需要的话
                    ),
                  ),
                ),
                Expanded(
                  flex: 1, //设置权重
                  child: GestureDetector(
                    onTap: () {
                      // 请求焦点
                      FocusScope.of(context).requestFocus(FocusNode());
                      if (type == 2) {
                        return;
                      }
                      setState(() {
                        type = 2;
                        textEditingController.text = "";
                        cycleCountSku.total = 0;
                        cycleCountSku.lpnQty = 0;
                        cycleCountSku.inventoryList = null;
                        getTallyContainerNo();
                      });
                    },
                    child: Container(
                      padding: EdgeInsets.all(5),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: type == 2 ? MyAppTheme.nearlyBlue : MyAppTheme.white, // 背景颜色
                        borderRadius: BorderRadius.only(topRight: Radius.circular(8.0), bottomRight: Radius.circular(8.0)), // 圆角半径
                        border: Border.all(
                          color: MyAppTheme.nearlyBlue, // 边框颜色
                          width: 0.5, // 边框宽度
                        ),
                      ),
                      child: Text(
                        'Return',
                        style: type == 2 ? MyAppTheme.textWhite14 : MyAppTheme.text,
                      ), // 子控件，如果需要的话
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 0, top: 5, right: 0, bottom: 0),
            width: double.infinity,
            child: ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 35),
              child: TextField(
                controller: textEditingController,
                textInputAction: TextInputAction.search,
                onSubmitted: (String text) {
                  print('Searching for $text');
                  if (text == null) {
                    return;
                  }
                  toSku(text);
                },
                // autofocus: true,
                decoration: InputDecoration(
                  suffixIcon: IconButton(
                    icon: Icon(
                      Icons.qr_code_scanner,
                      size: 20,
                      color: MyAppTheme.nearlyBlue,
                    ),
                    onPressed: () {
                      // requestPermissions();
                      // Utils.scanBarcode(context);
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                        return ScanCode();
                      })).then((text) {
                        if (text == null) {
                          return;
                        }
                        print(text); //拿到扫描结果
                        toSku(text);
                      });
                    },
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: MyAppTheme.nearlyBlue,
                    ),
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点之外的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点时的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  hintText: "scan inbound lpn barcode",
                  filled: true,
                  fillColor: MyAppTheme.white,
                  //隐藏下划线
                  //border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                ),
              ),
            ),
          ),
          SizedBox(
            height: 5,
          ),
          Row(
            children: [
              Expanded(
                flex: 1,
                child: Text(
                  "LPN QTY: ${Utils.getStringisInteger(cycleCountSku.total)}",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                ),
              ),
              Expanded(
                flex: 1,
                child: Text(
                  "Total: ${Utils.getStringisInteger(cycleCountSku.lpnQty)}",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                ),
              ),
            ],
          ),
          Row(
            children: [
              Expanded(
                flex: 1,
                child: Text(
                  "Location",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                ),
              ),
              Expanded(
                flex: 1,
                child: Text(
                  "QTY(IBLPN)",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                ),
              ),
            ],
          ),
          Expanded(
            child: Container(
              margin: EdgeInsets.only(left: 0, right: 0, top: 0),
              child: setListView(),
            ),
          ),
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      itemCount: cycleCountSku.inventoryList == null ? 0 : cycleCountSku.inventoryList.length,
      itemBuilder: (context, index) {
        InventoryListDTO tally = cycleCountSku.inventoryList[index];
        if (tally.isCheck == null) {
          tally.isCheck = false;
        }

        return Column(
          children: [
            Visibility(
                visible: index == 0 ? true : false,
                child: SizedBox(
                  height: 5,
                )),
            Row(
              children: [
                Expanded(
                  flex: 1, //设置权重
                  child: Text(
                    Utils.getStringisEmpty(tally.wholeCode),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                  ),
                ),
                Expanded(
                  flex: 1, //设置权重
                  child: Row(
                    children: [
                      Expanded(
                        flex: 2, //设置权重
                        child: Text(
                          Utils.isEmpty(tally.lpn) ? "${Utils.getStringisInteger(tally.quantity)}(--)" : "${Utils.getStringisInteger(tally.quantity)}(${Utils.getStringisEmpty(tally.lpn)})",
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                        ),
                      ),
                      SizedBox(
                        width: 5,
                      ),
                      Visibility(
                        visible: tally.isCheck ? true : false,
                        child: Container(
                            margin: EdgeInsets.only(
                              left: 5,
                            ),
                            child: Icon(
                              Icons.check,
                              size: 20,
                              color: MyAppTheme.nearlyBlue,
                            )),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            Divider(),
          ],
        );
      },
    );
  }

  @override
  void setNext() {
    ToastContext().init(context);
    if (Utils.isEmpty(textEditingController.text)) {
      Toast.show("Please select Drop Date", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    toSku(textEditingController.text);
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
    });
  }

  void getTallyContainerNo() async {
    Map<String, dynamic> map = new HashMap();
    map["sku"] = cycleCountSku.barcode;
    map["inventoryType"] = type;
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.cycleCountSkuSearch, params: map);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        CycleCountSku cycleCountSkuTemp = CycleCountSku.fromJson(baseResponse.data);
        cycleCountSkuTemp.barcode = cycleCountSku.barcode;
        cycleCountSku = cycleCountSkuTemp;
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void toSku(String lpn) async {
    Map<String, dynamic> map = new HashMap();
    map["sku"] = cycleCountSku.barcode;
    map["lpn"] = lpn;
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.cycleCountSkuDetail, params: map);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        InventoryListDTO inventoryListDTO = InventoryListDTO.fromJson(baseResponse.data);
        if (inventoryListDTO == null) {
          return;
        }
        cycleCountSku.inventory = inventoryListDTO;
        if (Utils.getIntegerisEmpty(inventoryListDTO.isNewReturn) == 1) {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => CCSkuTrkScreen(cycleCountSku: cycleCountSku)),
          ).then((value) {
            if (value == null) {
            } else if (value is bool) {
              Navigator.pop(context, true);
            } else if (value is CycleCountSku) {
              CycleCountSku cycleCountSku2 = value;
              if (cycleCountSku2 == null) {
                Navigator.pop(context, cycleCountSku2);
              }
              setState(() {
                textEditingController.text = "";
                hint = "";
                cycleCountSku = cycleCountSku2;
              });
            }
          }).catchError((error) {
            // 错误处理
            print("An error occurred: $error");
          });
          return;
        }
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => CCSkuSubmitScreen(cycleCountSku: cycleCountSku)),
        );
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }
}
